package com.example.userlogincenter.userCenter.controller;

import api.apiservice.apiopenplat.entity.ApiInfo;
import api.apiservice.apiopenplat.service.IApiInfoService;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import com.example.userlogincenter.userCenter.common.unifyDataForm.Result;
import com.example.userlogincenter.userCenter.common.unifyDataForm.ResultVo;
import com.example.userlogincenter.userCenter.entity.ApiMember;
import com.example.userlogincenter.userCenter.entity.CenterUser;
import com.example.userlogincenter.userCenter.pojo.*;
import com.example.userlogincenter.userCenter.service.ApiMemberService;
import com.example.userlogincenter.userCenter.service.ICenterUserService;
import com.example.userlogincenter.userCenter.util.JWTUtils;
import com.example.userlogincenter.userCenter.util.encrypUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Tangshen
 * @since 2022-11-02
 */
@RestController
@CrossOrigin
@RequestMapping("/centerUser")
@Api(tags = "用户控制器")
public class CenterUserController {

    @DubboReference
    private IApiInfoService apiInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ICenterUserService centerUserService;

    @Autowired
    private ApiMemberService apiMemberService;


    /**
     *
     * 查询所有用户
     *
     * */
    @GetMapping("alluser")
    public Result alluser(){
        ArrayList<userListVo> userListVos = new ArrayList<>();
        List<CenterUser> list = centerUserService.list();
        for (CenterUser centerUser:list){
            userListVo uservos = new userListVo();
            BeanUtils.copyProperties(centerUser,uservos);
            userListVos.add(uservos);
        }
        return Result.success(userListVos);
    }

    @GetMapping("getUser/{id}")
    public Result getUser(@PathVariable("id") Long id){
        CenterUser centerUser =  centerUserService.getUserById(id);
        return Result.success(centerUser);
    }


    @PostMapping("/userLogin")
    @ApiOperation(value = "用户登录")
    public Result UserLogin(@RequestBody userLoginVo loginUser) throws UnsupportedEncodingException {
        Subject subject = SecurityUtils.getSubject();
        CenterUser user = centerUserService.getOneByPhone(loginUser.getPhonenumber());
        String encrypPass = encrypUtils.encrypValue(loginUser.getUserpassword(), user.getSalt());
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginUser.getPhonenumber(), encrypPass);
        try{
            subject.login(usernamePasswordToken);
            //查询用户，获取该用户的id，手机末4位，昵称
            tokenUser tokenUser =  centerUserService.findUser(loginUser.getPhonenumber());
            //生成token
            HashMap<String,Object> tokenMap = new  HashMap<String,Object>();
            tokenMap.put("userId", tokenUser.getUserId());
            tokenMap.put("nickName", tokenUser.getNickname());
            String token = JWTUtils.generateJWT(tokenMap, tokenUser.getUserphone());
            //token存入redis中
            redisTemplate.opsForValue().set("token", token);
            //登陆成功
            return Result.success(token);
        }catch (UnknownAccountException uae){
            //用户ID不存在
            return Result.error(ResultVo.ERROR_IDNOTEXIST);
        }catch (IncorrectCredentialsException ice){
            //用户密码错误
            return Result.error(ResultVo.ERROR_PASSWORD);
        }
    }


    @PostMapping("/userRegister")
    @ApiOperation(value = "用户注册")
    public Result UserRegister(@RequestBody userRegisterVo registerUser) throws UnsupportedEncodingException {
        //判断验证码
        String rverificationCode = (String) redisTemplate.opsForValue().get("RverificationCode");
        if (!registerUser.getRverificationCode().equals(rverificationCode)) {
            return Result.error(ResultVo.ERROR_VCODE);
        }
        boolean saveResult = centerUserService.saveUser(registerUser);
        if (saveResult){
            return Result.success();
        }
        return Result.error(ResultVo.ERROR_UNKOWN);
    }


    @GetMapping("/userLoginOut")
    @ApiOperation(value = "用户注销")
    public Result UserLoginOut(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        //清除token
        redisTemplate.opsForValue().set("token","");
        return Result.success();
    }


    @GetMapping("/userInfo")
    @ApiOperation(value = "获取用户信息")
    public Result getUserInfo(){
        Map<String,String> map = new HashMap<>();
        map.put("token","[admin]");
        map.put("roles","[admin]");
        return Result.success(map);
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录-临时")
    public Result testUserLoigin(){
        System.out.println("进入登录页面");
        Map<String,String> map = new HashMap<>();
        map.put("name","admin");
        map.put("password","111111");
        map.put("roles","[admin,vip]");
        return Result.success(map);
    }

    @GetMapping("/getVerificationCode/{phone}")
    @ApiOperation(value = "获取手机验证码")
    public Result getVerificationCode(@PathVariable("phone") String phoneNumber) throws Exception {
        boolean  result = centerUserService.getVerificationCode(phoneNumber);
        if (result) {
            return Result.success();
        }
        return Result.error(ResultVo.ERROR_UNKOWN);
    }


    @GetMapping("/getMemberByToken/{token}")
    @ApiOperation(value = "根据token获取用户信息")
    public Result<CenterUser> getMemberByToken(@PathVariable("token") String token){
        final JWT jwt = JWTUtil.parseToken(token);
        jwt.getHeader(JWTHeader.TYPE);
        Long userId = Long.valueOf(String.valueOf(jwt.getPayload("userId")) );
        CenterUser loginUser = centerUserService.getUserById(userId);
        return Result.success(loginUser);
    }


    @GetMapping("/getMemberInfo/{userId}")
    @ApiOperation(value = "获取用户信息")
    public Result getMemberInfo(@PathVariable("userId")Long userId){
        memeberInfo Info = apiMemberService.getMemberInfo(userId);
        return Result.success(Info);
    }

    @GetMapping("getApiInfoById/{aid}")
    @ApiOperation(value = "获取API信息")
    public Result<ApiInfo> getApiInfoById(@PathVariable("aid")Long aid){
        ApiInfo apiInfoResult = apiInfoService.searchApiById(aid);
        return Result.success(apiInfoResult);
    }

}
